import '@umijs/max';
import React, { useEffect, useState } from 'react';
import { Card, Col, message, Row, Select } from 'antd';
import { serviceUsageUsingPost } from '@/services/api/sysStatistics';
import EChartsReact from 'echarts-for-react';
import { Statistic } from '@ant-design/pro-components';
import { FundProjectionScreenOutlined } from '@ant-design/icons';

/**
 * 统计分析页面
 *
 * @constructor
 */
const StatisticsPage: React.FC = () => {
  const [loading, setLoading] = useState<boolean>(false);
  const [data, setData] = useState<API.ServiceUsageResponse>({});

  const [params, setParams] = useState<API.ServiceUsageQueryRequest>({
    top: 10,
  });

  const [tokensConsumer, setTokensConsumer] = useState<any>({
    accountList: [],
    data: [],
    invokeCount: [],
  });

  /**
   * 构建数据
   */
  const buildOptionParams = (data: API.ServiceUsageResponse) => {
    if (data.top) {
      const tokensDataList: { value: number | undefined; name: string | undefined }[] = [];
      const invokeCountList: { value: number | undefined; name: string | undefined }[] = [];
      const accountList: (string | undefined)[] = [];

      data.top.forEach((item) => {
        tokensDataList.push({ value: item.tokensConsumed, name: item.sysUserVO?.userAccount });
        invokeCountList.push({ value: item.useCount, name: item.sysUserVO?.userAccount });
        accountList.push(item.sysUserVO?.userAccount);
      });
      setTokensConsumer({
        accountList: accountList,
        data: tokensDataList,
        invokeCount: invokeCountList,
      });
    }
  };

  /**
   * 加载数据
   */
  const loadData = async () => {
    try {
      setLoading(true);
      const res = await serviceUsageUsingPost(params);
      if (res.data) {
        setData(res.data);
        buildOptionParams(res.data);
      } else {
        message.error('获取统计数据失败');
      }
    } catch (e: any) {
      message.error('获取统计数据失败 ' + e.message);
    }
    setLoading(false);
  };

  /**
   * 搜索参数
   */
  useEffect(() => {
    loadData();
  }, []);

  const getColor = (index: number): string => {
    const colors = [
      '#FF6347',
      '#4682B4',
      '#32CD32',
      '#FFD700',
      '#9ACD32',
      '#8B008B',
      '#FF69B4',
      '#00BFFF',
    ];
    return colors[index % colors.length];
  };

  return (
    <div className="statistics-page">
      <Row
        gutter={{
          xs: 1,
          sm: 1,
          md: 2,
          lg: 2,
          xl: 3,
        }}
      >
        <Col xs={24} sm={24} md={24} lg={24} xl={24} style={{ marginBottom: 3 }}>
          <Card loading={loading}>
            <Row gutter={8}>
              <Col span={8}>
                <Card bordered={false} hoverable={true}>
                  <Statistic
                    title="总调用次数"
                    value={data.useCount}
                    valueStyle={{ color: 'red' }}
                    prefix={<FundProjectionScreenOutlined />}
                    suffix={'次'}
                  />
                </Card>
              </Col>
              <Col span={8}>
                <Card bordered={false} hoverable={true}>
                  <Statistic
                    title="总消耗Tokens"
                    value={data.totalConsumer}
                    valueStyle={{ color: 'red' }}
                    prefix={<FundProjectionScreenOutlined />}
                    suffix={'tokens'}
                  />
                </Card>
              </Col>
              <Col span={8}>
                <Card bordered={false} hoverable={true}>
                  <Statistic
                    title="单次调用平均消耗Tokens"
                    value={
                      data.totalConsumer && data.useCount
                        ? (data.totalConsumer / data.useCount).toFixed(3)
                        : 0
                    }
                    valueStyle={{ color: 'red' }}
                    prefix={<FundProjectionScreenOutlined />}
                    suffix={'tokens/次'}
                  />
                </Card>
              </Col>
            </Row>
          </Card>
        </Col>
        <Col xs={24} sm={24} md={12} lg={12} xl={12} style={{ marginBottom: 3 }}>
          <Card
            title={'调用次数(Top' + params.top + ')'}
            loading={loading}
            extra={
              <Select
                style={{ minWidth: 100 }}
                onChange={(value) => {
                  setParams({ top: value });
                }}
                defaultValue={params.top}
              >
                <Select.Option value={5}>Top5</Select.Option>
                <Select.Option value={10}>Top10</Select.Option>
                <Select.Option value={15}>Top15</Select.Option>
              </Select>
            }
          >
            <EChartsReact
              option={{
                title: {
                  text: '调用次数占比',
                  left: 'center',
                },
                tooltip: {
                  trigger: 'item',
                  formatter: '{a} <br/>{b} : {c} ({d}%)',
                },
                legend: {
                  orient: 'vertical',
                  left: 'left',
                  data: tokensConsumer.accountList,
                },
                series: [
                  {
                    name: '调用次数',
                    type: 'pie',
                    radius: '55%',
                    center: ['50%', '60%'],
                    data: tokensConsumer.invokeCount.map((item: any, index: any) => ({
                      ...item,
                      itemStyle: {
                        color: getColor(index), // 使用自定义函数来获取颜色
                      },
                    })),
                    emphasis: {
                      itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)',
                      },
                    },
                  },
                ],
              }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={24} md={12} lg={12} xl={12} style={{ marginBottom: 3 }}>
          <Card title={'Token消耗(Top' + params.top + ')'} loading={loading}>
            <EChartsReact
              option={{
                title: {
                  text: 'Token消耗占比',
                  left: 'center',
                },
                tooltip: {
                  trigger: 'item',
                  formatter: '{a} <br/>{b} : {c} ({d}%)',
                },
                legend: {
                  orient: 'vertical',
                  left: 'left',
                  data: tokensConsumer.accountList,
                },
                series: [
                  {
                    name: 'Token消耗',
                    type: 'pie',
                    radius: '55%',
                    center: ['50%', '60%'],
                    data: tokensConsumer.data,
                    emphasis: {
                      itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)',
                      },
                    },
                  },
                ],
              }}
            />
          </Card>
        </Col>
      </Row>
    </div>
  );
};
export default StatisticsPage;
